<template>
	<el-dialog title="表格显示列设置" v-model="visible" :close-on-click-modal="false" destroy-on-close draggable width="420px">
		<div>
			<div class="flex items-center">
				<span>拖动</span>
				<el-icon class="mx-2 cursor-move" :size="14"><Rank /></el-icon>
				<span>调整顺序</span>
			</div>
			<el-scrollbar height="400px">
				<el-checkbox-group ref="columnOptionsRef" v-model="checkedKeys">
					<div v-for="item in columnOptions" :key="item.prop" class="flex items-center">
						<div class="pr-[24px] cursor-move table-column-drag-icon">
							<el-icon :size="16"><Rank /></el-icon>
						</div>
						<el-checkbox :label="item.prop">{{ item.label }}</el-checkbox>
					</div>
				</el-checkbox-group>
			</el-scrollbar>
		</div>
		<template #footer>
			<span class="flex justify-between dialog-footer">
				<div>
					<el-button @click="resetColumns" type="warning" v-if="form.id">重置为默认</el-button>
				</div>
				<div>
					<el-button @click="visible = false">取消</el-button>
					<el-button type="primary" @click="onSubmit" :disabled="loading">确认</el-button>
				</div>
			</span>
		</template>
	</el-dialog>
</template>

<script setup lang="ts" name="ColumnSetting">
import Sortablejs from 'sortablejs';
import { tableColumnsType } from '../data';
import { cloneDeep } from 'lodash';
import { validateNull } from '/@/utils/validate';
import { addObj, getObj, putObj, delObjs } from '/@/api/platform/basicCustomizeTable';
import { useMessage, useMessageBox } from '/@/hooks/message';
import { useUserInfo } from '/@/stores/userInfo';
const userStores = useUserInfo();
const { userInfos } = storeToRefs(userStores);
const emit = defineEmits(['refresh', 'reset']);

// 定义变量内容
const visible = ref(false);
const loading = ref(false);
const columnOptions = ref<tableColumnsType[]>([]);
const columnOptionsRef = ref();
const checkedKeys = ref<string[]>([]);
const form = reactive({
	id: '',
	tableName: '',
	tableContent: '',
	userId: userInfos.value.user.userId,
	deptId: userInfos.value.user.deptId,
});

// 打开弹窗
const openDialog = async (id: string, tableName: string, cols: tableColumnsType[]) => {
	visible.value = true;
	form.id = '';
	form.tableName = tableName;
	if (id) {
		form.id = id;
		getbasicCustomizeTableData(id);
	}
	columnOptions.value = cloneDeep(cols);
	checkedKeys.value = cols.filter((d: tableColumnsType) => d.show).map((d) => d.prop);
	await init();
};

const getbasicCustomizeTableData = (id: string) => {
	// 获取数据
	loading.value = true;
	getObj(id)
		.then((res: any) => {
			Object.assign(form, res.data);
		})
		.finally(() => {
			loading.value = false;
		});
};
// 提交
const onSubmit = async () => {
	try {
		loading.value = true;

		for (let i = 0; i < columnOptions.value.length; i++) {
			const col_item = columnOptions.value[i];
			const index = checkedKeys.value.findIndex((d) => d === col_item.prop);
			if (index !== -1) {
				col_item.show = true;
			} else {
				col_item.show = false;
			}
		}
		const tableContent = cloneDeep(columnOptions.value);
		form.tableContent = JSON.stringify(tableContent);
		form.id ? await putObj(form) : await addObj(form);
		useMessage().success(form.id ? '修改成功' : '添加成功');
		visible.value = false;
		emit('refresh', tableContent);
	} catch (err: any) {
		useMessage().error(err.msg);
	} finally {
		loading.value = false;
	}
};

const init = async () => {
	await nextTick();
	const el = columnOptionsRef.value.$el;
	Sortablejs.create(unref(el), {
		animation: 500,
		delay: 400,
		delayOnTouchOnly: true,
		handle: '.table-column-drag-icon',
		dataIdAttr: 'data-no',
		onEnd: (evt: any) => {
			const { oldIndex, newIndex } = evt;
			if (validateNull(oldIndex) || validateNull(newIndex) || oldIndex === newIndex) {
				return;
			}
			const options = cloneDeep(columnOptions.value);
			// 排序
			if (oldIndex > newIndex) {
				options.splice(newIndex, 0, options[oldIndex]);
				options.splice(oldIndex + 1, 1);
			} else {
				options.splice(newIndex + 1, 0, options[oldIndex]);
				options.splice(oldIndex, 1);
			}

			// 更新 列可选项
			columnOptions.value = options;
		},
	});
};
const resetColumns = async () => {
	try {
		await useMessageBox().confirm('确定要重置列设置吗？');
	} catch {
		return;
	}

	try {
		await delObjs([form.id]);
		useMessage().success('重置成功');
		visible.value = false;
		emit('reset');
	} catch (err: any) {
		useMessage().error(err.msg);
	}
};
// 暴露变量
defineExpose({
	openDialog,
});
</script>
